import React, { useState, useCallback, useEffect } from 'react'
import { Layout, Button, Space, Typography, Modal, message, Spin } from 'antd'
import { 
  ArrowLeftOutlined, 
  SaveOutlined, 
  PlusOutlined,
  EyeOutlined,
  SettingOutlined,
  ClockCircleOutlined
} from '@ant-design/icons'
import { SceneGrid } from './SceneGrid'
import { ShotEditor } from './ShotEditor'
import { SceneDetailPanel } from './SceneDetailPanel'
import { TimelineView } from '../TimelineView'
import { StoryboardScene, StoryboardData, ShotType, CameraAngle, CameraMovement } from '../../../types/document'
import { useDocumentState } from '../../state/document/useDocumentState'
import './SceneCard/styles.css'

const { Header, Content } = Layout
const { Title } = Typography

export interface StoryboardEditorProps {
  contentId?: string
  onBack?: () => void
  onSave?: (storyboard: StoryboardData) => void
}

type EditMode = 'grid' | 'scene' | 'shot' | 'timeline'

/**
 * 分镜编辑器主组件
 * 整合场景网格、镜头编辑器和场景详情面板
 */
export const StoryboardEditor: React.FC<StoryboardEditorProps> = ({
  contentId,
  onBack,
  onSave
}) => {
  const { currentDocument, updateDocument, isLoading } = useDocumentState()
  const [editMode, setEditMode] = useState<EditMode>('grid')
  const [selectedSceneId, setSelectedSceneId] = useState<string | null>(null)
  const [isCreatingScene, setIsCreatingScene] = useState(false)

  // 获取当前分镜数据
  const storyboard = currentDocument?.data as StoryboardData | undefined
  const scenes = storyboard?.scenes || []

  // 获取选中的场景
  const selectedScene = selectedSceneId 
    ? scenes.find(scene => scene.id === selectedSceneId)
    : null

  // 处理场景选择 (支持时间线视图)
  const handleSceneSelect = useCallback((sceneId: string | null) => {
    setSelectedSceneId(sceneId)
    if (sceneId && editMode === 'grid') {
      setEditMode('scene')
    }
  }, [editMode])

  // 处理场景编辑
  const handleSceneEdit = useCallback((sceneId: string) => {
    setSelectedSceneId(sceneId)
    setEditMode('shot')
  }, [])

  // 处理场景删除
  const handleSceneDelete = useCallback((sceneId: string) => {
    Modal.confirm({
      title: '确认删除场景',
      content: '删除后无法恢复，确定要删除这个场景吗？',
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const updatedScenes = scenes.filter(scene => scene.id !== sceneId)
          // 重新排序
          updatedScenes.forEach((scene, index) => {
            scene.order = index
          })
          
          await updateStoryboard({ scenes: updatedScenes })
          
          // 如果删除的是当前选中场景，返回网格视图
          if (selectedSceneId === sceneId) {
            setSelectedSceneId(null)
            setEditMode('grid')
          }
          
          message.success('场景删除成功')
        } catch (error) {
          console.error('删除场景失败:', error)
          message.error('删除场景失败')
        }
      }
    })
  }, [scenes, selectedSceneId])

  // 处理场景复制
  const handleSceneDuplicate = useCallback(async (sceneId: string) => {
    try {
      const sourceScene = scenes.find(scene => scene.id === sceneId)
      if (!sourceScene) return

      const duplicatedScene: StoryboardScene = {
        ...sourceScene,
        id: `scene_${Date.now()}`,
        title: `${sourceScene.title} (副本)`,
        order: scenes.length
      }

      const updatedScenes = [...scenes, duplicatedScene]
      await updateStoryboard({ scenes: updatedScenes })
      
      message.success('场景复制成功')
    } catch (error) {
      console.error('复制场景失败:', error)
      message.error('复制场景失败')
    }
  }, [scenes])

  // 处理场景预览
  const handleScenePreview = useCallback((sceneId: string) => {
    // TODO: 实现场景预览功能
    message.info('场景预览功能开发中...')
  }, [])

  // 处理场景拖拽排序
  const handleSceneMove = useCallback(async (fromIndex: number, toIndex: number) => {
    try {
      const updatedScenes = [...scenes]
      const [movedScene] = updatedScenes.splice(fromIndex, 1)
      updatedScenes.splice(toIndex, 0, movedScene)
      
      // 更新排序
      updatedScenes.forEach((scene, index) => {
        scene.order = index
      })
      
      await updateStoryboard({ scenes: updatedScenes })
    } catch (error) {
      console.error('场景排序失败:', error)
      message.error('场景排序失败')
    }
  }, [scenes])

  // 处理添加场景
  const handleSceneAdd = useCallback(async () => {
    setIsCreatingScene(true)
    try {
      const newScene: StoryboardScene = {
        id: `scene_${Date.now()}`,
        title: `场景 ${scenes.length + 1}`,
        description: '',
        order: scenes.length,
        content: '',
        shot: {
          type: ShotType.MEDIUM,
          angle: CameraAngle.EYE_LEVEL,
          movement: CameraMovement.STATIC
        },
        timing: {
          duration: 5
        },
        sceneLocation: {
          name: '未设置地点',
          type: 'interior',
          lighting: 'natural_day'
        },
        elements: {
          characters: [],
          props: []
        },
        audioElements: {},
        visual: {},
        production: {
          priority: 'normal',
          complexity: 'simple',
          requiredCrew: []
        },
        attachments: {}
      }

      const updatedScenes = [...scenes, newScene]
      await updateStoryboard({ scenes: updatedScenes })
      
      // 自动选择新创建的场景
      setSelectedSceneId(newScene.id)
      setEditMode('shot')
      
      message.success('场景创建成功')
    } catch (error) {
      console.error('创建场景失败:', error)
      message.error('创建场景失败')
    } finally {
      setIsCreatingScene(false)
    }
  }, [scenes])

  // 处理场景更新
  const handleSceneUpdate = useCallback(async (updates: Partial<StoryboardScene>) => {
    if (!selectedSceneId) return

    try {
      const sceneIndex = scenes.findIndex(scene => scene.id === selectedSceneId)
      if (sceneIndex === -1) return

      const updatedScenes = [...scenes]
      updatedScenes[sceneIndex] = { ...updatedScenes[sceneIndex], ...updates }
      
      await updateStoryboard({ scenes: updatedScenes })
    } catch (error) {
      console.error('更新场景失败:', error)
      message.error('更新场景失败')
    }
  }, [scenes, selectedSceneId])

  // 更新分镜数据
  const updateStoryboard = async (updates: Partial<StoryboardData>) => {
    if (!currentDocument) return

    const updatedStoryboard: StoryboardData = {
      ...storyboard,
      ...updates,
      // 重新计算总时长
      totalDuration: updates.scenes ? 
        updates.scenes.reduce((total, scene) => total + (scene.timing?.duration || scene.duration || 0), 0) :
        storyboard?.totalDuration || 0
    }

    await updateDocument({
      ...currentDocument,
      data: updatedStoryboard
    })
  }

  // 保存分镜
  const handleSave = async () => {
    if (storyboard) {
      onSave?.(storyboard)
      message.success('分镜保存成功')
    }
  }

  // 返回网格视图
  const handleBackToGrid = () => {
    setSelectedSceneId(null)
    setEditMode('grid')
  }

  // 渲染工具栏
  const renderToolbar = () => (
    <Header style={{ background: '#fff', padding: '0 16px', borderBottom: '1px solid #f0f0f0' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          {editMode !== 'grid' && (
            <Button
              icon={<ArrowLeftOutlined />}
              onClick={handleBackToGrid}
            >
              返回场景列表
            </Button>
          )}
          <Title level={4} style={{ margin: 0 }}>
            {editMode === 'grid' && '分镜编辑器'}
            {editMode === 'timeline' && '时间线视图'}
            {editMode === 'scene' && selectedScene && `场景详情 - ${selectedScene.title}`}
            {editMode === 'shot' && selectedScene && `镜头编辑 - ${selectedScene.title}`}
          </Title>
        </Space>

        <Space>
          {editMode === 'grid' && (
            <Button
              icon={<ClockCircleOutlined />}
              onClick={() => setEditMode('timeline')}
            >
              时间线视图
            </Button>
          )}
          {editMode === 'shot' && (
            <Button
              icon={<SettingOutlined />}
              onClick={() => setEditMode('scene')}
            >
              场景设置
            </Button>
          )}
          {editMode === 'scene' && (
            <Button
              icon={<EyeOutlined />}
              onClick={() => setEditMode('shot')}
            >
              镜头编辑
            </Button>
          )}
          <Button
            type="primary"
            icon={<SaveOutlined />}
            onClick={handleSave}
          >
            保存分镜
          </Button>
          {onBack && (
            <Button onClick={onBack}>
              退出编辑
            </Button>
          )}
        </Space>
      </div>
    </Header>
  )

  // 渲染内容区域
  const renderContent = () => {
    if (isLoading) {
      return (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '400px' 
        }}>
          <Spin size="large" tip="加载分镜数据...">
            <div style={{ minHeight: '200px' }} />
          </Spin>
        </div>
      )
    }

    switch (editMode) {
      case 'grid':
        return (
          <SceneGrid
            scenes={scenes}
            selectedSceneId={selectedSceneId}
            onSceneSelect={handleSceneSelect}
            onSceneEdit={handleSceneEdit}
            onSceneDelete={handleSceneDelete}
            onSceneDuplicate={handleSceneDuplicate}
            onScenePreview={handleScenePreview}
            onSceneMove={handleSceneMove}
            onSceneAdd={handleSceneAdd}
          />
        )
      
      case 'timeline':
        return (
          <TimelineView
            scenes={scenes}
            selectedSceneId={selectedSceneId}
            onSceneSelect={handleSceneSelect}
            onSceneReorder={handleSceneMove}
          />
        )
      
      case 'scene':
        return selectedScene ? (
          <SceneDetailPanel
            scene={selectedScene}
            onChange={handleSceneUpdate}
          />
        ) : null
      
      case 'shot':
        return selectedScene ? (
          <ShotEditor
            scene={selectedScene}
            onChange={handleSceneUpdate}
          />
        ) : null
      
      default:
        return null
    }
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {renderToolbar()}
      
      <Content style={{ padding: '24px', background: '#f5f5f5' }}>
        {renderContent()}
      </Content>
    </Layout>
  )
}

export default StoryboardEditor